#include "AudioSource.h"
#include "core/Util.h"

using namespace SolidityEngine;

AudioSource::AudioSource():
    Component(),
    _loop(false),
    _playonwake(true),
    _volume(1.0),
    _clip(NULL),
    _channel(-1)
{
    //ctor
}

AudioSource::~AudioSource()
{
    //dtor
}

void AudioSource::SetPlayOnWake(bool flag)
{
    _playonwake=flag;
}

void AudioSource::SetLooping(bool flag)
{
    _loop=flag;
}

bool AudioSource::IsLooping()
{
    return _loop;
}

bool AudioSource::IsLooping() const
{
    return _loop;
}

bool AudioSource::IsPlaying()
{
    if(_channel!=-1){
        if(Mix_Playing(_channel)!=0){
            return true;
        }
    }
    return false;
}

bool AudioSource::IsPlaying() const
{
    if(_channel!=-1){
        if(Mix_Playing(_channel)!=0){
            return true;
        }
    }
    return false;
}

void AudioSource::_OnStart()
{
    if(_playonwake) Play();
}

void AudioSource::Play()
{
    if(_clip){
        _clip->GetChunk()->volume=ClampI(0,128,(int)(_volume*128));
        int flag = _loop ? -1 : 0;
        _channel=Mix_PlayChannel(-1, _clip->GetChunk(), flag);
    }
}

void AudioSource::Stop()
{
    if(_channel!=-1 && IsPlaying()) Mix_HaltChannel(_channel);
}

void AudioSource::SetVolume(float volume)
{
    _volume=volume;
}

void AudioSource::SetAudioClip(AudioClip* clip)
{
    _clip=clip;
}

AudioClip* AudioSource::GetAudioClip()
{
    return _clip;
}

const AudioClip* AudioSource::GetAudioClip() const
{
    return _clip;
}

AudioSource* AudioSource::_Clone()
{
     return new AudioSource(*this);
}
